What is @storybook/preview-api?
The @storybook/preview-api package is part of the Storybook ecosystem, which is a tool for developing UI components in isolation for React, Vue, Angular, and more. This package provides APIs to interact with the Storybook preview, allowing developers to control the rendering of stories, listen to events, and manipulate the state of the Storybook UI.
What are @storybook/preview-api's main functionalities?
Fetching and rendering stories
This feature allows developers to fetch story data by ID and render it using a custom component or utility.
import { useStorybookApi } from '@storybook/api';
function MyComponent() {
const api = useStorybookApi();
const story = api.getData('some-story-id');
return <StoryRenderer story={story} />;
}
Listening to Storybook events
This feature enables components to listen to Storybook-specific events and react accordingly, as well as emit events to the Storybook environment.
import { useEffect } from 'react';
import { useChannel } from '@storybook/api';
function MyComponent() {
const emit = useChannel({
'storybook/my-event': (eventData) => {
console.log('Event data:', eventData);
}
});
useEffect(() => {
emit('storybook/my-event', { payload: 'data' });
}, [emit]);
return <div>Check the console for event data.</div>;
}
Manipulating the Storybook UI
Developers can use this feature to programmatically control the Storybook UI, such as changing the current story displayed.
import { addons } from '@storybook/addons';
addons.setChannel(new Channel({ transport: new PostmsgTransport({ key: 'iframe-key' }) }));
addons.getChannel().emit('setCurrentStory', { storyId: 'some-story-id' });
Other packages similar to @storybook/preview-api
@storybook/addon-actions
This package allows developers to create callbacks that appear in the actions panel of the Storybook UI when clicked. It is similar to @storybook/preview-api in that it enhances the Storybook development experience but focuses on actions rather than preview functionality.
@storybook/addon-links
This package provides a way to create links between stories. It is similar to @storybook/preview-api in that it interacts with the Storybook UI, but it specifically focuses on linking stories together rather than providing a general API for preview manipulation.
@storybook/addon-storysource
This addon shows the source of the story next to the story itself. While it enhances the Storybook experience by providing source code context, it does not offer an API for controlling the preview like @storybook/preview-api does.